package com.project.api.common.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.api.common.Unit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class LoginToken {
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**token保留时间，单位秒**/
    private final static int expire = 7200;
    public static String NAME="admin_token";
    public static String ADMIN="admin_id";
    private static String token;
    private static String uid;
    public static String Get(){
        return token;
    }

    /**
     * 设置token
     * @param sid  session_id
     * @param u  数据库userid
     * @return
     */
    public static String Set(String sid,String u){
        if (sid == null || u == null) return null;
        long time = System.currentTimeMillis();
        time = time + expire * 1000;
        JSONObject obj=new JSONObject();
        obj.put("sid",sid);
        obj.put("uid",u);
        obj.put("expire",time);
//        uid=u;
        return Unit.Base64Encode(obj.toJSONString());
    }

    /**
     * 验证token合法性
     * @param token 当前请求session里token
     * @param t 当前请求token
     * @return
     */
    public static boolean Verify(String token,String t){
        if (t==null || token == null) return false;
        long time = System.currentTimeMillis();
        String objString = Unit.Base64Decode(t);
        JSONObject resObj= JSON.parseObject(objString);
        String dsid= (String) resObj.getOrDefault("sid",null);
        String duid= (String) resObj.getOrDefault("uid",null);
        long dtime= (Long) resObj.getOrDefault("expire",0);

        String o = Unit.Base64Decode(token);
        JSONObject obj= JSON.parseObject(o);
        String osid= (String) obj.getOrDefault("sid",null);
        String ouid= (String) obj.getOrDefault("uid",null);
        long otime= (Long) obj.getOrDefault("expire",0);
        if (dsid == null || !dsid.equalsIgnoreCase(osid))return false;
        if (duid == null || !duid.equalsIgnoreCase(ouid) )return false;
        if ( otime<=time )return false;
//        uid=duid;
        return true;
    }
    public static String reflesh(String token){
        if(token!=null){
            long time = System.currentTimeMillis();
            String objString = Unit.Base64Decode(token);
            JSONObject resObj= JSON.parseObject(objString);
            time = time + expire * 1000;
            long dtime= time;
            resObj.put("expire",dtime);
            return  Unit.Base64Encode(resObj.toJSONString());
        }
        return null;
    }
    public static String Uid(){
        return uid;
    }
}
